package com.czk.server;

import com.czk.domain.TransferProtocol;
import com.czk.domain.User;
import com.czk.service.UserService;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/4/26 10:34
 */
@Component
public class MyNettyServerHandler extends ChannelInboundHandlerAdapter {
    @Autowired
    private UserService userService;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 拿到客户端通道
        Channel channel = ctx.channel();
        System.out.println("链接报告开始");
        System.out.println("链接报告信息：有一客户端链接到本服务端。channelId：" + channel.id());
        System.out.println("链接报告IP:" + channel.localAddress());
        System.out.println("链接报告Port:" + channel.localAddress());
        System.out.println("链接报告完毕");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端断开连接" + ctx.channel().localAddress());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()) + "服务端接收消息" + msg);
        // 转换
        if (msg instanceof TransferProtocol) {
            // 强壮
            TransferProtocol transferProtocol = (TransferProtocol) msg;
            // 拿到传输对象
            Object obj = transferProtocol.getObj();
            if (obj instanceof User) {
                User user = (User) obj;
                userService.save(user);
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("服务端异常" + cause.getMessage());
        ctx.close();

    }
}
